package br.com.ime.usp.cmep;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;

import br.com.ime.usp.cmep.BandexUtils.BandexAccessor;
import br.com.ime.usp.cmep.BandexUtils.BandexNetworkAccessor;
import br.com.ime.usp.cmep.BandexUtils.BandexComment;
import br.com.ime.usp.cmep.CardapioActivity.MockBandexStatusListAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Comparator;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.Action;
import com.markupartist.android.widget.ActionBar.IntentAction;

public class RatingActivity extends Activity{
	private ArrayList<String> listItems = new ArrayList<String>();
	private ArrayAdapter<String> adapter;
	private boolean downloading = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rating);
		
		// configura actionbar
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle(getString(R.string.rating_titulo));
        actionBar.setHomeAction(new HomeAction(this));        
        actionBar.addAction(new RefreshAction(this));
        actionBar.addAction(new BackAction(this));
		
		// formulario
		final Spinner s1 = (Spinner) findViewById(R.id.rating_bandex);
		final Spinner s2 = (Spinner) findViewById(R.id.rating_fila);
		final Button enviar = (Button) findViewById(R.id.rating_enviar);
		final EditText comentario = (EditText) findViewById(R.id.rating_comentario);
		
		ArrayAdapter a1 = ArrayAdapter.createFromResource(this, R.array.bandexs, android.R.layout.simple_spinner_item);
		a1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s1.setAdapter(a1);
	    
		ArrayAdapter a2 = ArrayAdapter.createFromResource(this, R.array.tamanho_fila, android.R.layout.simple_spinner_item);
		a2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    s2.setAdapter(a2);
	    s2.setSelection(2); // fila media
	    
		enviar.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(comentario.getText().toString().trim().length() > 0) {
					Intent intent = new Intent(RatingActivity.this, SendRatingActivity.class);
					intent.putExtra("bandex", s1.getSelectedItem().toString());
					intent.putExtra("comentario", comentario.getText().toString());
					intent.putExtra("fila", s2.getSelectedItem().toString());
					startActivity(intent);
					finish();
				}
				else
					Toast.makeText(getApplicationContext(), getString(R.string.rating_envionulo), Toast.LENGTH_SHORT).show();
			}
		});
		
		// baixe as coisas
		download();
	}
	
	
	// esta baixando os dados da rede?
	public boolean isDownloading() { 
		return downloading;
	}
	
	// baixe os dados da rede
	public void download() {
		final ProgressBar d = (ProgressBar) findViewById(R.id.rating_downloading);
		d.setVisibility(ProgressBar.VISIBLE);
	    ListView lv = (ListView)findViewById(R.id.rating_lista);
	    lv.setVisibility(ListView.INVISIBLE);
		
	    downloading = true;
	    new DownloadRatingsTask().execute(); // baixa lista de comentarios em outra thread
	}
	
	
	
	
	// ----------------
	

	
	// cria lista de comentarios
	private void createRatingList(ArrayList<BandexComment> lst) {
	    ListView lv = (ListView)findViewById(R.id.rating_lista);
	    lv.setVisibility(ListView.VISIBLE);
	    lv.setAdapter( new BandexCommentListAdapter(this, R.id.rating_lista, lst) );
	    lv.setClickable(false);
	    
	    if(lv.getCount() == 0)
	    	Toast.makeText(getApplicationContext(), getString(R.string.rating_semcomentarios), Toast.LENGTH_SHORT).show();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// fazer uma listinha personalizada...
	// quanto trampo!!!!
	public class BandexCommentListAdapter extends ArrayAdapter<BandexComment> {
	    private int resource;
	    private ArrayList<BandexComment> items;

	    public BandexCommentListAdapter(Context context, int resource, ArrayList<BandexComment> items) {
	        super(context, resource, items);
	        this.resource = resource;
	        this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        View v = convertView;
	        if (v == null) {
	        	LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        	v = vi.inflate(R.layout.rating_comment, null);
	        }
	        
	        BandexComment item = (BandexComment) items.get(position);
	        if (item != null) {
	        	TextView bandex = (TextView) v.findViewById(R.id.ratingcomment_bandex);
	        	TextView hora = (TextView) v.findViewById(R.id.ratingcomment_hora);
	        	TextView texto = (TextView) v.findViewById(R.id.ratingcomment_texto);
	        	
	        	if(bandex != null)
	        		bandex.setText((String)item.getBandex());

	        	if(hora != null)
	        		hora.setText(convertHora((String)item.getHora()));
	        	
	        	if(texto != null)
	        		texto.setText((String)item.getTexto());
	        }
	        
	        return v;
	    }
	    
	    private String convertHora(String str) {
	    	// delta t
	    	Date d1, d2;
	    	Calendar cal = Calendar.getInstance();
	    	cal.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
	    	try {
	    		SimpleDateFormat s = new SimpleDateFormat("ss-mm-HH-dd-MM-yy");
	    		s.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));//"GMT+04:00"));
				d1 = s.parse(str);
			} catch (ParseException e) {
				d1 = cal.getTime();
			}
	    	d2 = cal.getTime();
	    	long diff = Math.max(0, d2.getTime() - d1.getTime());
	    	
	    	// detalhezinhos
	    	long timeInSeconds = diff / 1000;
	    	long hours, minutes, seconds;
	    	//hours = timeInSeconds / 3600;
	    	//timeInSeconds = timeInSeconds - (hours * 3600);
	    	minutes = timeInSeconds / 60;
	    	timeInSeconds = timeInSeconds - (minutes * 60);
	    	seconds = timeInSeconds;
	    	
	    	// pronto
	    	return "há " + minutes + " min";
	    }
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// ----------- AsyncTask ------------
	
	private class DownloadRatingsTask extends AsyncTask<Void, Void, ArrayList<BandexComment> > {
		/** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		private String error = "";
		
	    protected ArrayList<BandexComment> doInBackground(Void... foo) {
	    	ArrayList<BandexComment> data = new ArrayList<BandexComment>();
	    	
	    	try {
		    	// lista de bandexs
			    String[] bandexList = BandexUtils.getList();
			    BandexAccessor ba = new BandexNetworkAccessor();
			    
			    // quero todas as entradas dos jsons de todos os bandexs
			    for(String bandex : bandexList)
			    	data.addAll( ba.getBandexComments(bandex) );
			    
			    // ordene por horario (decrescente)
			    Collections.sort(data, new Comparator<BandexComment>() {
			    	public int compare(BandexComment a, BandexComment b) {
						try {
							long d1 = (new SimpleDateFormat("ss-mm-HH-dd-MM-yy")).parse(a.getHora()).getTime();
							long d2 = (new SimpleDateFormat("ss-mm-HH-dd-MM-yy")).parse(b.getHora()).getTime();
							return (int)(d2 - d1);
						}
						catch(Exception e) {
							return 0;
						}
			    	}
			    });
	    	}
	    	catch(Exception e){
	    		error = e.getMessage();
	    	}
			
			// pronto
			return data;
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(ArrayList<BandexComment> result) {
	    	if(error.equals(""))
	    		goBack(result);
	    	else
	    		goBack(error);
	    }
	}
	
	// goBack() e' chamado pela AsyncTask
	protected void goBack(ArrayList<BandexComment> data) {
		downloading = false;
		
	    // tira a bolinha girando
		final ProgressBar d = (ProgressBar) findViewById(R.id.rating_downloading);
		d.setVisibility(ProgressBar.INVISIBLE);
		//((LinearLayout)d.getParent()).removeView(downloading);
		
	    // cria a listinha bonita
	    createRatingList(data);
	}
	
	protected void goBack(String error) {
		downloading = false;
		
		// toasty!!!
		Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
		
	    // tira a bolinha girando
		final ProgressBar d = (ProgressBar) findViewById(R.id.rating_downloading);
		d.setVisibility(ProgressBar.INVISIBLE);
		//((LinearLayout)d.getParent()).removeView(downloading);
	}
	
	
	
	
	
	
	// --------- coisas da actionbar ---------------
	
	// volta para a tela anterior
    private class BackAction extends AbstractAction {
    	private Activity act;
        public BackAction(Activity a) {
            super(R.drawable.ic_action_back); act = a;
        }
        public void performAction(View view) {
            act.finish();
        }
    }
    
    // atualiza lista
    private class RefreshAction extends AbstractAction {
    	private RatingActivity act;
        public RefreshAction(RatingActivity a) {
            super(R.drawable.ic_action_refresh); act = a;
        }
        public void performAction(View view) {
            if(!act.isDownloading())
            	act.download();
        }
    }
    
    // volta pra home
    private class HomeAction extends AbstractAction {
    	private Activity act;
        public HomeAction(Activity a) {
            super(R.drawable.ic_launcher); act = a;
        }
        public void performAction(View view) {
        	Intent i = new Intent(act, CMEPActivity.class);
        	act.startActivity(i);
        	act.finish();
        }
    }
}
